import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
} from "@/components/ui/sidebar";

import { Separator } from "@/components/ui/separator";
import { SearchForm } from "./search-form";
import { useEffect } from "react";
import { useConversationStore } from "@/store/useConversationStore";
import { Avatar, AvatarFallback, AvatarImage } from "./ui/avatar";
import { useNavigate } from "react-router";
import { sessionApi } from "@/api/session";
import { useChatStore } from "@/store/useChatStore";
import { useUserStore } from "../store/useUserStore";
import Home from "../assets/home.svg";
import Role from "../assets/role.svg";
import Logo from "../assets/logo.png";
import { ScrollArea } from "@/components/ui/scroll-area";
import { NavUser } from "./sidebar-user";

const items = [
  {
    title: "Home",
    url: "/",
    icon: Home,
  },
  {
    title: "Role",
    url: "/role",
    icon: Role,
  },
];

export function AppSidebar() {
  const { selectedId, setSelectedId, conversations, fetchConversations } =
    useConversationStore();
  const { messages, addMessage } = useChatStore();
  const { user } = useUserStore();
  const navigate = useNavigate();
  useEffect(() => {
    fetchConversations();
  }, [fetchConversations]);

  const handleConversationClick = async (id: string) => {
    setSelectedId(id);
    navigate(`/conversation/${id}`);

    if (messages.get(id) !== undefined) {
      return;
    }

    const { data } = await sessionApi.getChatHistory(id);
    data.forEach((message) => {
      addMessage({
        id: message.id,
        content: [
          {
            type: "text",
            content: message.content,
          },
        ],
        role: message.role,
      });
    });
    console.log("messages", messages);
  };

  return (
    <Sidebar>
      <SidebarHeader>
        <SidebarMenuButton className="h-[70px]" asChild>
          <a href="/">
            <img
              className="h-[42px] w-[42px] rounded-3xl"
              src={Logo}
              alt="logo"
            />
            <span className="font-extrabold text-xl">RoleMate.ai</span>
          </a>
        </SidebarMenuButton>
        <SidebarMenu>
          {items.map((item) => (
            <SidebarMenuItem key={item.title}>
              <SidebarMenuButton
                className="h-[50px] hover:bg-gray-200 rounded-2xl"
                asChild
              >
                <a href={item.url}>
                  <img src={item.icon} alt={item.title} className="h-6 ml-2" />
                  <span className="font-bold text-[16px]">{item.title}</span>
                </a>
              </SidebarMenuButton>
            </SidebarMenuItem>
          ))}
        </SidebarMenu>
        <Separator />
        <div className="flex w-full max-w-sm items-center gap-2">
          <SearchForm />
        </div>
      </SidebarHeader>
      <SidebarContent>
        <ScrollArea className="h-full">
          <SidebarGroup className="space-y-1">
            {conversations.length > 0 &&
              conversations.map((item) => (
                <SidebarMenuItem
                  key={item.id}
                  className={
                    selectedId === item.id + "" ? "bg-gray-200 rounded-3xl" : ""
                  }
                >
                  <SidebarMenuButton
                    className="h-[48px] hover:bg-gray-200 rounded-3xl"
                    onClick={() => handleConversationClick(item.id + "")}
                    asChild
                  >
                    <div>
                      <Avatar>
                        <AvatarImage src={item.roleAvatarUrl} />
                        <AvatarFallback>CN</AvatarFallback>
                      </Avatar>
                      <span>{item.roleName}</span>
                    </div>
                  </SidebarMenuButton>
                </SidebarMenuItem>
              ))}
          </SidebarGroup>
        </ScrollArea>
      </SidebarContent>
      <Separator />
      <SidebarFooter>
        <NavUser user={user} />
      </SidebarFooter>
    </Sidebar>
  );
}
